package com.dlc.shop.allinpay.listener;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dlc.shop.allinpay.service.AllinpayService;
import com.dlc.shop.bean.dto.AppConnectDTO;
import com.dlc.shop.bean.dto.allinpay.ApplyBindAcctDTO;
import com.dlc.shop.bean.event.allinpay.CreateAllinpayMemberEvent;
import com.dlc.shop.bean.model.UserExtension;
import com.dlc.shop.common.allinpay.constant.AllinpayConstant;
import com.dlc.shop.common.allinpay.member.constant.PayAcctType;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.enums.SysTypeEnum;
import com.dlc.shop.service.UserExtensionService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author gaozijie
 * @date 2023-08-09
 */
@Component
@AllArgsConstructor
public class CreateAllinpayMemberListener {

    private final AllinpayService allinpayService;

    private final UserExtensionService userExtensionService;

    private static final Logger logger = LoggerFactory.getLogger(CreateAllinpayMemberListener.class);

    /**
     * 批量创建通联个人会员
     * @param event
     */
    @EventListener(CreateAllinpayMemberEvent.class)
    public void batchCreateMember(CreateAllinpayMemberEvent event) {
        List<String> userIds = event.getUserIds();
        if (CollectionUtils.isEmpty(userIds)) {
            return;
        }
        // 批量创建通联会员
        List<String> createdUserIds = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (String userId : userIds) {
            try {
                allinpayService.createMember(AllinpayConstant.USER + userId, SysTypeEnum.ORDINARY.value());
                createdUserIds.add(userId);
                logger.info("用户[{}]，创建通联个人会员成功", userId);
            } catch (Exception e) {
                if (e.getMessage().contains("已经存在此用户")) {
                    createdUserIds.add(userId);
                }
                logger.error("用户[{}]，创建通联个人会员失败: {}", userId, e.getMessage());;
            }
        }
        event.setSuccessCount(createdUserIds.size());
        // 更新状态为'已创建'
        if (!CollectionUtils.isEmpty(createdUserIds)) {
            userExtensionService.update(new LambdaUpdateWrapper<UserExtension>()
                    .set(UserExtension::getAllinpayCreate, 1)
                    .in(UserExtension::getUserId, userIds));
        }
        // 绑定支付标识
        List<AppConnectDTO> appConnects = event.getAppConnects();
        if (CollectionUtils.isEmpty(appConnects)) {
            return;
        }
        List<String> updateUserIds = new ArrayList<>(Constant.INITIAL_CAPACITY);
        ApplyBindAcctDTO applyBindAcctDTO;
        for (AppConnectDTO appConnectDTO : appConnects) {
            try {
                applyBindAcctDTO = new ApplyBindAcctDTO();
                applyBindAcctDTO.setAcct(appConnectDTO.getTempUid());
                applyBindAcctDTO.setAcctType(Objects.equals(appConnectDTO.getAppId(), 1) ? PayAcctType.WECHAT_MINI_PROGRAM.value() : PayAcctType.WECHAT_PUBLIC.value());
                allinpayService.applyBindAcct(AllinpayConstant.USER + appConnectDTO.getUserId(), applyBindAcctDTO);
                updateUserIds.add(appConnectDTO.getUserId());
                logger.info("用户[{}]通联支付用户标识[{}]绑定成功", appConnectDTO.getUserId(), appConnectDTO.getTempUid());
            } catch (Exception e) {
                logger.error("用户[{}]通联支付用户标识[{}]绑定失败，原因为：{}", appConnectDTO.getUserId(), appConnectDTO.getTempUid(), e.getMessage());
            }
        }
        // 更新用户拓展信息（已绑定支付标识）
        if (!CollectionUtils.isEmpty(updateUserIds)) {
            userExtensionService.update(new LambdaUpdateWrapper<UserExtension>()
                    .set(UserExtension::getAllinpayPayAcctBind, 1)
                    .in(UserExtension::getUserId, updateUserIds));
        }
    }
}
